package com.example.wechat.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.wechat.ChatActivity;
import com.example.wechat.adapter.ConversationAdapter;
import com.example.wechat.R;
import com.example.wechat.model.Conversation;
import java.util.ArrayList;
import java.util.List;

public class ChatFragment extends Fragment {
    private RecyclerView recyclerView;
    private ConversationAdapter adapter;
    private List<Conversation> conversations;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_chat, container, false);
        initViews(view);
        loadConversations();
        return view;
    }

    private void initViews(View view) {
        recyclerView = view.findViewById(R.id.recycler_view);
        if (recyclerView == null) {
            throw new IllegalStateException("RecyclerView not found in layout");
        }
        
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        conversations = new ArrayList<>();
        adapter = new ConversationAdapter(conversations);
        adapter.setOnItemClickListener((conversation) -> {
            Intent intent = new Intent(getActivity(), ChatActivity.class);
            intent.putExtra("contact_id", conversation.getContactId());
            intent.putExtra("contact_name", conversation.getContactName());
            startActivity(intent);
        });
        recyclerView.setAdapter(adapter);
    }

    private void loadConversations() {
        // 这里应该从数据库加载会话列表
        // 临时使用测试数据
        conversations.clear();
        conversations.add(new Conversation("1", "张三", "你好，最近怎么样？", System.currentTimeMillis()));
        conversations.add(new Conversation("2", "李四", "周末一起吃饭吧", System.currentTimeMillis() - 3600000));
        conversations.add(new Conversation("3", "王五", "项目进展如何？", System.currentTimeMillis() - 7200000));
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onResume() {
        super.onResume();
        loadConversations(); // 每次返回时刷新会话列表
    }
} 